package com.black.utils.commons.display;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author ylx
 */
public class InfoPanel extends JPanel {

    private final JScrollPane scrollPane;
    private final JPanel infoPanel;

    private InfoPanel() {
        setLayout(new CardLayout());
        infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        scrollPane = new JScrollPane(infoPanel);
        infoPanel.setBackground(InfoFrame.BACKGROUND);
        add(scrollPane);
    }

    public static JLabel printInfo(String info) {
        InfoPanel instance = getInstance();
        JLabel label = new JLabel(info);
        label.setForeground(Color.WHITE);
        instance.infoPanel.add(label);
        instance.updateUI();
        JScrollBar verticalScrollBar = instance.scrollPane.getVerticalScrollBar();
        verticalScrollBar.setValue(verticalScrollBar.getMaximum());
        return label;
    }

    public static JLabel printInfo(String... infos) {
        String str = String.join("\t | ", infos);
        return printInfo(str);
    }

    public static void printInfo(Object... infos) {
        String[] array = Arrays.stream(infos).map(String::valueOf).collect(Collectors.toList()).toArray(new String[]{});
        printInfo(array);
    }

    public static void printUrl(String url) {
        JLabel label = printInfo("<html><u>", url, "</u></html>");
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    File dir = new File(url);
                    Desktop.getDesktop().open(dir);
                } catch (IOException ex) {
                    InfoPanel.printInfo(ex.getMessage());
                }
            }
        });
    }

    public static InfoPanel getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final InfoPanel INSTANCE = new InfoPanel();
    }
}
